package com.bocai.kelalacar.ui.driver.set.act;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bocai.kelalacar.App;
import com.bocai.kelalacar.R;
import com.bocai.kelalacar.base.BaseActivity;
import com.bocai.kelalacar.bean.PutDriverBean;
import com.bocai.kelalacar.bean.TravelInformationBean;
import com.bocai.kelalacar.bean.UploadImgBean;
import com.bocai.kelalacar.ui.car.main.act.MainActivity;
import com.bocai.kelalacar.ui.car.set.module.SetModule;
import com.bocai.kelalacar.ui.driver.set.contract.DriverCertificationContract;
import com.bocai.kelalacar.ui.driver.set.module.DriverCertificationModule;
import com.bocai.kelalacar.ui.driver.set.presenter.DriverCertificationPresenter;
import com.bocai.kelalacar.util.SP;
import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;

/**
 * Created by yuanfei on 2017/6/26.
 */

public class DriverCertificationInformationActivity extends BaseActivity implements DriverCertificationContract.view{
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.add_name)
    EditText addName;
    @BindView(R.id.add_phone)
    EditText addPhone;
    @BindView(R.id.add_id_card)
    EditText addIdCard;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.add_img_driving_license)
    ImageView addImgDrivingLicense;
    @BindView(R.id.ll_look_img_driving_license)
    LinearLayout llLookImgDrivingLicense;
    @BindView(R.id.add_img_jiashi_license)
    ImageView addImgJiashiLicense;
    @BindView(R.id.ll_look_img_jiashi_license)
    LinearLayout llLookImgJiashiLicense;
    @BindView(R.id.add_img_transport_license)
    ImageView addImgTransportLicense;
    @BindView(R.id.ll_look_img_transport_license)
    LinearLayout llLookImgTransportLicense;
    @BindView(R.id.add_img_transport_certificate)
    ImageView addImgTransportCertificate;
    @BindView(R.id.ll_look_img_transport_certificate)
    LinearLayout llLookImgTransportCertificate;
    @BindView(R.id.add_img_insurance_card)
    ImageView addImgInsuranceCard;
    @BindView(R.id.ll_look_img_insurance_card)
    LinearLayout llLookImgInsuranceCard;
    @BindView(R.id.btn_next)
    Button btnNext;
    private String imgUrl1,imgUrl2,imgUrl3,imgUrl4,imgUrl5;
    private PutDriverBean bean = new PutDriverBean();
    @Inject
    DriverCertificationPresenter presenter;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    int flag = 0;

    @Override
    public int getLayoutId() {
        return R.layout.act_driver_cer_infor;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new DriverCertificationModule(this)).inject(this);
    }

    @Override
    public void initView() {
        initToolbar("认证信息");
        initBack(imgBack,llBack);
        addName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())&&addPhone.getText().toString().length()==11
                        &&!TextUtils.isEmpty(addIdCard.getText().toString())&&(addIdCard.getText().toString().length() == 15||addIdCard.getText().toString().length() == 18)
                        &&!TextUtils.isEmpty(imgUrl1)&&!TextUtils.isEmpty(imgUrl2)&&!TextUtils.isEmpty(imgUrl3)&&!TextUtils.isEmpty(imgUrl4)&&!TextUtils.isEmpty(imgUrl5)){
                    btnNext.setEnabled(true);
                }else {
                    btnNext.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        addPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())&&addPhone.getText().toString().length()==11
                        &&!TextUtils.isEmpty(addIdCard.getText().toString())&&(addIdCard.getText().toString().length() == 15||addIdCard.getText().toString().length() == 18)
                        &&!TextUtils.isEmpty(imgUrl1)&&!TextUtils.isEmpty(imgUrl2)&&!TextUtils.isEmpty(imgUrl3)&&!TextUtils.isEmpty(imgUrl4)&&!TextUtils.isEmpty(imgUrl5)){
                    btnNext.setEnabled(true);
                }else {
                    btnNext.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        addIdCard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())&&addPhone.getText().toString().length()==11
                        &&!TextUtils.isEmpty(addIdCard.getText().toString())&&(addIdCard.getText().toString().length() == 15||addIdCard.getText().toString().length() == 18)
                        &&!TextUtils.isEmpty(imgUrl1)&&!TextUtils.isEmpty(imgUrl2)&&!TextUtils.isEmpty(imgUrl3)&&!TextUtils.isEmpty(imgUrl4)&&!TextUtils.isEmpty(imgUrl5)){
                    btnNext.setEnabled(true);
                }else {
                    btnNext.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R.id.add_img_driving_license,R.id.add_img_jiashi_license,R.id.add_img_transport_license,R.id.add_img_transport_certificate,R.id.add_img_insurance_card,
            R.id.btn_next})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.add_img_driving_license:
                flag = 111;
                checkReadPermission();
                break;
            case R.id.add_img_jiashi_license:
                flag = 222;
                checkReadPermission();
                break;
            case R.id.add_img_transport_license:
                flag = 333;
                checkReadPermission();
                break;
            case R.id.add_img_transport_certificate:
                flag = 444;
                checkReadPermission();
                break;
            case R.id.add_img_insurance_card:
                flag = 555;
                checkReadPermission();
                break;
            case R.id.btn_next:
                if (TextUtils.isEmpty(addName.getText().toString())){
                    showShortToast("请输入姓名");
                }else if (TextUtils.isEmpty(addPhone.getText().toString())){
                    showShortToast("请输入联系电话");
                }else if (addPhone.getText().toString().length()!=11){
                    showShortToast("请输入正确的联系电话");
                }else if (TextUtils.isEmpty(addIdCard.getText().toString())){
                    showShortToast("请输入身份证号");
                }else if (addIdCard.getText().toString().length()!=18){
                    showShortToast("请输入正确的身份证号");
                }else if (TextUtils.isEmpty(imgUrl1)){
                    showShortToast("请选择行驶证");
                }else if (TextUtils.isEmpty(imgUrl2)){
                    showShortToast("请选择驾驶证");
                }else if (TextUtils.isEmpty(imgUrl3)){
                    showShortToast("请选择道路运输证");
                }else if (TextUtils.isEmpty(imgUrl4)){
                    showShortToast("请选择旅行运输从业资格证");
                }else if (TextUtils.isEmpty(imgUrl5)){
                    showShortToast("请选择承运人旅客责任保险卡");
                }else {
                    List<String> list = new ArrayList<>();
                    list.add(imgUrl1);list.add(imgUrl2);list.add(imgUrl3);list.add(imgUrl4);list.add(imgUrl5);
                    presenter.uploadImg(list);
                }
                break;
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                List<String> list = new ArrayList<>();
                List<String> photos = new ArrayList<>();
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                Log.e("photos", photos.get(0).toString());
                if (requestCode == 111){
                    imgUrl1 = photos.get(0).toString();
                    Glide.with(this).load(imgUrl1).into(addImgDrivingLicense);
                }else if (requestCode == 222){
                    imgUrl2 = photos.get(0).toString();
                    Glide.with(this).load(imgUrl2).into(addImgJiashiLicense);
                }else if (requestCode == 333){
                    imgUrl3 = photos.get(0).toString();
                    Glide.with(this).load(imgUrl3).into(addImgTransportLicense);
                }else if (requestCode == 444){
                    imgUrl4 = photos.get(0).toString();
                    Glide.with(this).load(imgUrl4).into(addImgTransportCertificate);
                }else if (requestCode == 555){
                    imgUrl5 = photos.get(0).toString();
                    Glide.with(this).load(imgUrl5).into(addImgInsuranceCard);
                }

                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())&&addPhone.getText().toString().length()==11
                        &&!TextUtils.isEmpty(addIdCard.getText().toString())&&(addIdCard.getText().toString().length() == 15||addIdCard.getText().toString().length() == 18)
                        &&!TextUtils.isEmpty(imgUrl1)&&!TextUtils.isEmpty(imgUrl2)&&!TextUtils.isEmpty(imgUrl3)&&!TextUtils.isEmpty(imgUrl4)&&!TextUtils.isEmpty(imgUrl5)){
                    btnNext.setEnabled(true);
                }else {
                    btnNext.setEnabled(false);
                }
            }
        }else if (requestCode == 5&&resultCode == 6){
            finish();
        }
    }

    public void doTakePhoto(){
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(this, flag);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkReadPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //应用还未获取读取本地文件 的权限，询问是否允许
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 222);
        } else {
            doTakePhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 111) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkReadPermission();
            } else {
                showErrorTip("权限被禁止，无法打开相机");
            }
        }else if (requestCode == 222){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doTakePhoto();
            } else {
                showErrorTip("权限被禁止，无法打开相机");
            }
        }
    }

    @Override
    public void putDriverInforSuccess() {

    }

    @Override
    public void uploadImgSuccess(UploadImgBean uploadImgBean) {

        bean.setDriverName(addName.getText().toString());
        bean.setDriverPhone(addPhone.getText().toString());
        bean.setIdNumber(addIdCard.getText().toString());
        bean.setDrivingLicenseId(uploadImgBean.getContent().get(0).getId());
        bean.setDriverLicenseId(uploadImgBean.getContent().get(1).getId());
        bean.setTransportLicenseId(uploadImgBean.getContent().get(2).getId());
        bean.setQualificationsLicenseId(uploadImgBean.getContent().get(3).getId());
        bean.setInsuranceCardId(uploadImgBean.getContent().get(4).getId());

        Intent intent = new Intent(DriverCertificationInformationActivity.this,DriverCertificationInformationSecondActivity.class);
        intent.putExtra("data",bean);
        startActivityForResult(intent,5);

    }


    @Override
    public void getTravelSuccess(TravelInformationBean bean) {

    }

    @Override
    public void optionalSeatsList(List<Integer> list) {

    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {
        showShortToast(msg);
        if (msg.equals("您的登录已失效，请重新登录")){
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }
    }
}
